package com.cnctema.easecalendar_weekly_view.activities

import android.app.*
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProviders
import com.google.android.material.snackbar.Snackbar
import com.cnctema.easecalendar_weekly_view.EVENT_ID
import com.cnctema.easecalendar_weekly_view.R
import com.cnctema.easecalendar_weekly_view.WEEK_START_TIMESTAMP
import com.cnctema.easecalendar_weekly_view.database.EventDatabase
import com.cnctema.easecalendar_weekly_view.databinding.ActivityAddEventBinding
import com.cnctema.easecalendar_weekly_view.extensions.config
import com.cnctema.easecalendar_weekly_view.extensions.hideKeyboard
import com.cnctema.easecalendar_weekly_view.utils.FormatterUtils
import com.cnctema.easecalendar_weekly_view.utils.FormatterUtils.DAYCODE_PATTERN
import com.cnctema.easecalendar_weekly_view.utils.FormatterUtils.TIME_24_PATTERN
import org.joda.time.DateTime
import kotlin.properties.Delegates

class AddEventActivity : AppCompatActivity() {
    private lateinit var binding: ActivityAddEventBinding
    lateinit var mViewModel: AddEventViewModel
    private var eventId by Delegates.notNull<Long>()    //传入的日程id

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        //获取intent
        val intent = intent?:return
        binding = DataBindingUtil.setContentView(this,R.layout.activity_add_event)

        //设置数据库映射
        val dataSource = EventDatabase.getInstance(application).eventDatabaseDao

        //设置viewModel
        mViewModel = ViewModelProviders
            .of(this, AddEventViewModelFactory(application = application,dataSource = dataSource))
            .get(AddEventViewModel::class.java)
        binding.viewModel = mViewModel

        // 初始化数据
        eventId = intent.getLongExtra(EVENT_ID,-1L)
        val weekTimestamp:Long = intent.getLongExtra(WEEK_START_TIMESTAMP,-1L)
        supportActionBar?.apply {
            title = if(eventId==-1L) getString(R.string.addEventActivity_name_add) else getString(R.string.addEventActivity_name_update)
            setHomeButtonEnabled(true)
            setDisplayHomeAsUpEnabled(true)
        }
        //初始化日程
        mViewModel.initializeCurrEvent(eventId,weekTimestamp,config.myName!!){event->

            val startDateTime = DateTime(event.startTimeMilli)
            val endDateTime = DateTime(event.endTimeMilli)
            binding.apply {
                //事件内容
                edTitle.setText(event.eventTitle)
                edLocation.setText(event.eventLocation)
                edDes.setText(event.eventDes)
                edInvitee.setText(event.eventInvitee)
                edInvitor.setText(event.eventInvitor)
                //事件标记
                spReMin.setSelection(event.eventReMin)
                spRepeat.setSelection(event.eventRepeat)
                btnIsPersonal.isSelected = event.eventIsPersonal
                //时间
                tvStartDate.text = startDateTime.toString(DAYCODE_PATTERN)
                tvEndDate.text = endDateTime.toString(DAYCODE_PATTERN)
                tvStartTime.text = startDateTime.toString(TIME_24_PATTERN)
                tvEndTime.text = endDateTime.toString(TIME_24_PATTERN)
            }
        }


        binding.apply {
            //设置日期按钮赋值监听
            dateStHolder.setOnClickListener{
                hideKeyboard()
                binding.dateStHolder.isClickable = false
                showDatePicker(DateTime(mViewModel.currEvent.startTimeMilli),0){
                    binding.dateStHolder.isClickable = true
                }
            }
            dateEndHolder.setOnClickListener{
                hideKeyboard()
                binding.dateEndHolder.isClickable = false
                showDatePicker(DateTime(mViewModel.currEvent.endTimeMilli), 1){
                    binding.dateEndHolder.isClickable = true
                }
            }
        }
    }

    //显示日期选择器
    private fun showDatePicker(dateTime: DateTime,sd_type:Int,
                               callback: ()->Unit){
        val picker = DatePickerDialog(this@AddEventActivity,
            DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
                mViewModel.resetDate(year,monthOfYear+1,dayOfMonth,sd_type){stDateTime, edDateTime,isRested ->
                    binding.tvStartDate.text = stDateTime.toString(DAYCODE_PATTERN)
                    binding.tvEndDate.text = edDateTime.toString(DAYCODE_PATTERN)

                    val sendDateTime = if (sd_type == 0) stDateTime else edDateTime
                    showTimePicker(sendDateTime,sd_type)
                }
                callback.invoke()
            },
            dateTime.year,
            dateTime.monthOfYear-1,
            dateTime.dayOfMonth)
        picker.show()
        picker.setOnCancelListener {
            callback.invoke()
        }
    }

    //显示时间选择器
    private fun showTimePicker(dateTime: DateTime,sd_type:Int){
        TimePickerDialog(
            this@AddEventActivity,
            TimePickerDialog.OnTimeSetListener { view, hourOfDay, minute ->
                mViewModel.resetTime(hourOfDay,minute,sd_type){stDateTime, edDateTime,isRested ->
                    binding.tvStartTime.text = FormatterUtils.getTimeString_24(stDateTime)
                    binding.tvEndTime.text = FormatterUtils.getTimeString_24(edDateTime)
                    if(isRested){
                        binding.tvStartDate.text = stDateTime.toString(DAYCODE_PATTERN)
                        binding.tvEndDate.text = edDateTime.toString(DAYCODE_PATTERN)
                    }
                }

            },
            dateTime.hourOfDay,
            dateTime.minuteOfHour,
            true).show()
    }

    // 保存日程
    private fun saveEvent(){
        mViewModel.currEvent.apply {
            eventTitle = binding.edTitle.text.toString()
            eventLocation = binding.edLocation.text.toString()
            eventDes = binding.edDes.text.toString()
            eventInvitee = binding.edInvitee.text.toString()
            eventInvitor = binding.edInvitor.text.toString()
            //标记
            eventIsPersonal = binding.swIsPersonal.isSelected
            eventReMin = binding.spReMin.selectedItemPosition
            eventRepeat = binding.spRepeat.selectedItemPosition
        }
        mViewModel.saveCurrEvent(){missType->
            when(missType){
                1->{
                    hideKeyboard()
                    Snackbar.make(binding.edTitle,"标题不能为空",Snackbar.LENGTH_SHORT)
                        .setAction("查看", View.OnClickListener {
                            binding.edTitle.requestFocus()
                            binding.edTitle.setHintTextColor(ContextCompat.getColor(this,R.color.colorAccent))
                            binding.scrollview.scrollY = 0
                        })
                        .show()
                }
                else-> {
                    finish()
                }
            }
        }
    }
    // 删除日程
    private fun deleteEventById(id:Long) {
        mViewModel.deleteEventById(id) {
            finish()
        }
    }

    // 设置菜单执行前方法
    override fun onPrepareOptionsMenu(menu: Menu): Boolean {
        // 根据是否为新建事件隐藏删除按钮
        menu.getItem(0).isVisible = eventId != -1L
        return super.onPrepareOptionsMenu(menu)
    }
    // 设置任务栏菜单内容
    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.menu_addevent, menu)
        return true
    }
    // 设置菜单操作
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.action_save -> {   //保存
                saveEvent()
                true
            }
            R.id.action_delete ->{  //删除
                deleteEventById(eventId)
                true
            }
            android.R.id.home->{    //返回上一级
                finish()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
}
